package com.genghis.ptas.clean.service.impl;

import com.genghis.ptas.clean.dao.DataCleanDao;
import com.genghis.ptas.clean.service.DataCleanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.GreedyStepwise;
import weka.core.Instances;
import weka.filters.Filter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: wangxiao
 * Date: 14-5-25
 * Time: 下午6:50
 * To change this template use File | Settings | File Templates.
 */
@Service("DataCleanService")
public class DataCleanServiceImpl implements DataCleanService {

    @Autowired
    private DataCleanDao dataCleanDao;

    @Override
    public Instances getInstances() {
        return dataCleanDao.getInstances();
    }

    @Override
    public Instances useFilter(Instances instances) {
        try {
            weka.filters.supervised.attribute.AttributeSelection filter = new weka.filters.supervised.attribute.AttributeSelection();
            CfsSubsetEval eval = new CfsSubsetEval();
            GreedyStepwise search = new GreedyStepwise();
            search.setSearchBackwards(true);
            filter.setEvaluator(eval);
            filter.setSearch(search);
            filter.setInputFormat(instances);
            return Filter.useFilter(instances, filter);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<String> getDataSet(List<String> dataSet, List<String> attr) {
        List<String> list = new ArrayList<String>();
        int clums = attr.size();
        int j = 0;
        String cl = "";
        for (int i = 0; i < dataSet.size(); i++) {
            if (j == clums) {
                cl = cl.substring(0, cl.length() - 1);
                list.add(cl);
                j = 0;
                cl = "";
            }
            cl = cl + "'" + dataSet.get(i) + "'" + ",";
            j++;
            if ((i + 1) == dataSet.size()) {
                cl = cl.substring(0, cl.length() - 1);
                list.add(cl);
                j = 0;
                cl = "";
            }
        }
        return list;
    }

    @Override
    public void insertDataSet(List<String> list, List<String> attr) {
        String arr = getArr(attr);
        dataCleanDao.cleanTable();
        for (String data : list) {
            dataCleanDao.insertDataSet(data, arr);
        }
    }

    @Override
    public void deleteClums(List<String> deleteAtte) {
        for (String str : deleteAtte) {
            dataCleanDao.dropClum(str);
        }
    }

    private String getArr(List<String> attr) {
        String clums = "";
        for (String cl : attr) {
            clums = clums + "`" + cl + "`,";
        }
        clums = clums.substring(0, clums.length() - 1);
        return clums;
    }
}
